package com.mg.service.impl;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mg.common.Constants;
import com.mg.common.ResponseJson;
import com.mg.dto.SimpleResult;
import com.mg.dto.UserDto;
import com.mg.mapper.BankCardMapper;
import com.mg.mapper.UserMapper;
import com.mg.model.BankCard;
import com.mg.model.User;
import com.mg.service.UserService;
import com.mg.utils.JsonUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by mg1213 on 2018/3/17.
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BankCardMapper bankCardMapper;
    private Logger logger = LogManager.getLogger(UserServiceImpl.class.getName());

    @Override
    public User login(HttpServletRequest request, User user) {
        HttpSession session = request.getSession();

        List<User> userList = userMapper.select(user);
        if (userList != null && userList.size() == 1) {
            session.setAttribute(Constants.USER_INFO, userList.get(0));
            return userList.get(0);
        }
        return new User();
    }

    @Override
    public ResponseJson<User> register(User user) {
        User tempUser = new User();
        tempUser.setPhoneNumber(user.getPhoneNumber());
        List<User> userList = userMapper.select(tempUser);
        if (userList != null && userList.size() > 0) {
            return new ResponseJson<>(500, "手机号码已存在!");
        }
        if (user.getFrozeMoney() == null) {
            user.setFrozeMoney(new BigDecimal(0.00));
        }
        if (user.getBalance() == null) {
            user.setBalance(new BigDecimal(0.00));
        }
        user.setCreateTime(new Date());
        int num = userMapper.insertSelective(user);
        if (num == 1) {
            return new ResponseJson<>(200, "注册成功");
        }
        return new ResponseJson<>(500, "注册失败");
    }

    @Override
    public ResponseJson<User> editPass(User user, String newPass) {
        List<User> userList = userMapper.select(user);
        if (userList != null && userList.size() == 1) {
            user.setUpdateTime(new Date());
            user.setPassword(newPass);
            int num = userMapper.updateByPrimaryKeySelective(user);
            if (num == 1) {
                return new ResponseJson<>(200, "修改成功");
            }
        }
        return new ResponseJson<>(500, "修改失败");
    }

    @Override
    public ResponseJson<User> getUserPass(User user) {
        User tempUser = new User();
        tempUser.setPhoneNumber(user.getPhoneNumber());
        List<User> userList = userMapper.select(tempUser);
        if (userList != null && userList.size() == 1) {
            user.setId(userList.get(0).getId());
            user.setUpdateTime(new Date());
            int num = userMapper.updateByPrimaryKeySelective(user);
            if (num == 1) {
                return new ResponseJson<>(200, "修改成功");
            }
        } else {
            return new ResponseJson<>(500, "用户不存在");
        }
        return new ResponseJson<>(500, "修改失败");
    }

    @Override
    public int insertUser(User user) {
        return userMapper.insertSelective(user);
    }

    @Override
    public PageInfo<UserDto> selectPageInfo(UserDto dto, int start, int limit) {
        PageHelper.offsetPage(start, limit);
        List<UserDto> userDtos = userMapper.selectAllUser(dto);
        PageInfo<UserDto> userDtoPageInfo = new PageInfo<>(userDtos);
        return userDtoPageInfo;
    }

    @Override
    public List<BankCard> getBankCardByUserId(Integer userId) {
        BankCard bankCard = new BankCard();
        bankCard.setUserId(userId);
        return bankCardMapper.select(bankCard);
    }

    @Override
    public SimpleResult deleteUser(String ids) {
        SimpleResult result = new SimpleResult();
        try {
            String[] idArr = ids.split(",");
            for (String id : idArr) {
                if ("-1".equals(id)) {
                    result.setSuccess(false);
                    result.setErrorCode(Constants.ERROR_CODE);
                    result.setErrorMessage("不能删除admin！");
                    return result;
                }
                BankCard bankCard = new BankCard();
                bankCard.setUserId(Integer.parseInt(id));
                bankCardMapper.delete(bankCard);
                userMapper.deleteByPrimaryKey(Integer.parseInt(id));
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(Constants.ERROR_CODE);
            result.setErrorMessage("删除失败！");
            logger.error("删除失败", e);
        }
        return result;
    }

    @Override
    public Map<String, Object> selectUserById(Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            User user1 = new User();
            user1.setId(id);
            List<User> userList = userMapper.select(user1);
            if (userList.isEmpty()) {
                result.put("success", false);
                result.put("errorMessage", "用户信息不存在");
            } else {
                userList.get(0).setPassword(null);
                BankCard bankCard = new BankCard();
                bankCard.setUserId(id);
                List<BankCard> bankCards = bankCardMapper.select(bankCard);
                result.put("user", userList.get(0));
                result.put("bankCards", bankCards);
                result.put("success", true);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("errorMessage", "系统未知异常");
            logger.error("系统未知异常", e);
        }
        return result;
    }

    @Override
    public SimpleResult updateUser(String userStr, String bankcards) {
        SimpleResult result = new SimpleResult();
        try {
            User user = JsonUtils.toBean(userStr, User.class);
            List<BankCard> bankCardList = JsonUtils.toList(bankcards, BankCard.class);
            User user1 = new User();
            user1.setId(user.getId());
            List<User> userList = userMapper.select(user1);
            if (userList.isEmpty() && user.getId() != null) {
                result.setSuccess(false);
                result.setMsg("用户信息不存在");
            } else {
                if (user.getId() != null) {
                    if (user.getId() == -1) {
                        user.setPhoneNumber(null);
                    }else{
                        if ("admin".equals(user.getPhoneNumber())) {
                            result.setSuccess(false);
                            result.setMsg("不能修改为admin");
                            return result;
                        }
                    }
                    user.setUpdateTime(new Date());
                    userMapper.updateByPrimaryKeySelective(user);
                } else {
                    if ("admin".equals(user.getPhoneNumber())) {
                        result.setSuccess(false);
                        result.setMsg("不能修改为admin");
                        return result;
                    }
                    userMapper.insertSelective(user);
                }

                BankCard bankCard1 = new BankCard();
                bankCard1.setUserId(user.getId());
                List<BankCard> oldBankCards = bankCardMapper.select(bankCard1);

                for (BankCard bankCard : bankCardList) {
                    bankCard.setUserId(user.getId());
                    Iterator<BankCard> iterator = oldBankCards.iterator();
                    while (iterator.hasNext()) {
                        BankCard bankCard2 = iterator.next();
                        if (bankCard2.getId().equals(bankCard.getId())) {
                            iterator.remove();
                        }
                    }
                    if (bankCard.getId() != null && bankCard.getId() != -1) {
                        bankCard.setUpdateTime(new Date());
                        bankCardMapper.updateByPrimaryKeySelective(bankCard);
                    } else {
                        bankCard.setId(null);
                        bankCard.setCreateTime(new Date());
                        bankCardMapper.insert(bankCard);
                    }
                }
                for (BankCard bankCard : oldBankCards) {
                    bankCardMapper.delete(bankCard);
                }
            }

        } catch (JsonParseException e) {
            result.setSuccess(false);
            result.setMsg("json 转换失败");
            logger.error("json 转换失败", e);
        } catch (JsonMappingException e) {
            result.setSuccess(false);
            result.setMsg("json 转换失败");
            logger.error("json 转换失败", e);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("系统未知异常");
            logger.error("系统未知异常", e);
        }
        return result;
    }

    @Override
    public List<User> getAllUsers() {
        return userMapper.selectAll();
    }

    @Override
    public User getUser(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    public SimpleResult updateUser(User user) {
        SimpleResult result = new SimpleResult();
        userMapper.updateByPrimaryKeySelective(user);
        return result;
    }

    @Override
    public PageInfo<BankCard> getBankInfo(Integer userId) {
        BankCard bankCard = new BankCard();
        bankCard.setUserId(userId);
        List<BankCard> bankCards = bankCardMapper.select(bankCard);
        PageInfo<BankCard> bankCardPageInfo = new PageInfo<>();
        bankCardPageInfo.setList(bankCards);
        return bankCardPageInfo;
    }

    @Override
    public SimpleResult saveBankInfo(BankCard bankCard) {
        SimpleResult result = new SimpleResult();
        if (bankCard.getId() == null) {
            bankCardMapper.insertSelective(bankCard);
        } else {
            bankCardMapper.updateByPrimaryKeySelective(bankCard);
        }
        return result;
    }

    @Override
    public SimpleResult deleteBankInfo(String ids, Integer userId) {
        SimpleResult result = new SimpleResult();
        try {
            String[] idArr = ids.split(",");
            for (String id : idArr) {
                BankCard bankCard = new BankCard();
                bankCard.setUserId(userId);
                bankCard.setId(Integer.parseInt(id));
                bankCardMapper.delete(bankCard);
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setErrorCode(Constants.ERROR_CODE);
            result.setErrorMessage("删除失败！");
            logger.error("删除失败", e);
        }
        return result;
    }


}
